package cn.com.ejiakanghu.web;

import cn.com.ejiakanghu.annotation.LoginUser;
import cn.com.ejiakanghu.core.utils.RespUtil;
import cn.com.ejiakanghu.core.vo.BaseResult;
import cn.com.ejiakanghu.dto.EjiaUserAddressInfo;
import org.apache.commons.lang3.StringUtils;
import org.linlinjava.litemall.core.util.RegexUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.dao.LitemallRegionMapper;
import org.linlinjava.litemall.db.domain.LitemallAddress;
import org.linlinjava.litemall.db.domain.LitemallRegion;
import org.linlinjava.litemall.db.service.LitemallAddressService;
import org.linlinjava.litemall.db.service.LitemallRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 地址相关
 *
 * @author houzb
 * @Description
 * @create 2021-03-29 19:14
 */
@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private LitemallAddressService addressService;
    @Autowired
    private LitemallRegionService litemallRegionService;

    /**
     * @api {get} /address/list 获取收货地址列表
     * @apiGroup 用户地址
     * @apiVersion 0.1.0
     * @apiDescription 根据登录用户获取已填写的收货地址列表
     * @apiSuccess {int} code 请求状态码，0表示成功,其它参考状态码文档
     * @apiSuccess {String} message 结果消息说明
     * @apiSuccess {boolean} success 请求是否成功
     * @apiSuccess {Object} data 请求响应的数据
     * @apiSuccessExample {json} Success-Response:
     *   {
     *     "code": "请求状态码，0表示成功，其它参考状态码文档",
     *     "success": "请求是否成功",
     *     "timestamp": "服务器当前时间戳10位精确到秒",
     *     "message": "请求成功/失败说明",
     *     "data": {
     *         "list": [{
     *             "id": "收货地址ID",
     *             "userId": "用户ID",
     *             "province": "省",
     *             "city": "市",
     *             "village": "区/县",
     *             "userName": "收货人姓名",
     *             "gender": "收货人性别",
     *             "phone": "收货人手机号",
     *             "isDefault": "是否是默认地址",
     *             "address": "收货地址",
     *             "detail": "详细地址门牌号",
     *             "lng": "经度",
     *             "lat": "纬度"
     *         }]
     *     }
     * }
     */
    @RequestMapping("/list")
    public BaseResult getUserAddressList(@LoginUser Integer userId) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        List<LitemallAddress> addressList = addressService.queryByUid(userId);
        List<EjiaUserAddressInfo> userAddressInfoList = EjiaUserAddressInfo.getListInstance(addressList);
        Map<String,Object> data = new HashMap<>();
        data.put("list", userAddressInfoList);
        return RespUtil.success(data);
    }

    /**
     * @api {get} /address/get 获取地址详情
     * @apiGroup 用户地址
     * @apiVersion 0.1.0
     * @apiDescription 用户的收货地址详情信息
     * @apiSuccess {Object} Object
     * @apiSuccessExample {json} Success-Response:
     * { "msg": "成功", "code":0, "data": {} }
     */
    @RequestMapping("/get")
    public BaseResult getAuserAddressInfo(@LoginUser Integer userId, @NotNull Integer id) {
        if (userId == null) {
            return RespUtil.unlogin();
        }

        LitemallAddress address = addressService.query(userId, id);
        if (address == null) {
            return RespUtil.fail();
        }
        return RespUtil.success(EjiaUserAddressInfo.getInstance(address));
    }

    private Object validate(LitemallAddress address) {
        String name = address.getName();
        if (StringUtils.isEmpty(name)) {
            return ResponseUtil.badArgument();
        }

        // 测试收货手机号码是否正确
        String mobile = address.getTel();
        if (StringUtils.isEmpty(mobile)) {
            return ResponseUtil.badArgument();
        }
        if (!RegexUtil.isMobileSimple(mobile)) {
            return ResponseUtil.badArgument();
        }

        String province = address.getProvince();
        if (StringUtils.isEmpty(province)) {
            return ResponseUtil.badArgument();
        }

        String city = address.getCity();
        if (StringUtils.isEmpty(city)) {
            return RespUtil.badArgument();
        }

        String county = address.getCounty();
        if (StringUtils.isEmpty(county)) {
            return RespUtil.badArgument();
        }


		/*String areaCode = address.getAreaCode();
		if (StringUtils.isEmpty(areaCode)) {
			return ResponseUtil.badArgument();
		}*/

		if(address.getLat() == null || address.getLng() == null) {
		    return RespUtil.badArgument();
        }
        String addressStr = address.getAddress();
        if (StringUtils.isEmpty(addressStr)) {
            return RespUtil.badArgument();
        }

        Boolean isDefault = address.getIsDefault();
        if (isDefault == null) {
            return RespUtil.badArgument();
        }
        return null;
    }


    /**
     * @api {get} /address/add 添加地址信息
     * @apiParam {String} province 省,必填
     * @apiParam {String} city 市,必填
     * @apiParam {String} village 区/县,必填
     * @apiParam {String} userName 收货人姓名,必填
     * @apiParam {number} gender 收货人性别,必填
     * @apiParam {String} phone 收货人手机号,必填
     * @apiParam {number} isDefault 是否默认地址,必填
     * @apiParam {String} address 收货地址
     * @apiParam {String} detail 详细地址门牌号
     * @apiParam {number} lng 经度
     * @apiParam {number} lat 纬度
     * @apiGroup 用户地址
     * @apiVersion 0.1.0
     * @apiDescription 用户添加地址信息
     * @apiSuccess {int} code 请求状态码，0表示成功,其它参考状态码文档
     * @apiSuccess {String} message 结果消息说明
     * @apiSuccess {boolean} success 请求是否成功
     * @apiSuccess {Object} data 请求响应的数据
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code": "请求状态码，0表示成功，其它参考状态码文档",
     *     "success": "请求是否成功",
     *     "timestamp": "服务器当前时间戳10位精确到秒",
     *     "message": "请求成功/失败说明",
     *     "data": "请求响应数据，对象或数组"
     * }
     */
    @RequestMapping("/add")
    public BaseResult addAddress(@LoginUser Integer userId, EjiaUserAddressInfo addressInfo) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        LitemallAddress address = EjiaUserAddressInfo.getInstanceLite(addressInfo);
        Object error = validate(address);
        if (error != null) {
            return RespUtil.badArgumentValue();
        }

        // 根据省名称查询省id
        Integer provinceId = litemallRegionService.getProvinceIdByName(address.getProvince());
        address.setProvinceId(provinceId);

        if (address.getId() == null || address.getId().equals(0)) {
            if (address.getIsDefault()) {
                // 重置其他收货地址的默认选项
                addressService.resetDefault(userId);
            }

            address.setId(null);
            address.setUserId(userId);
            addressService.add(address);
        } else {
            LitemallAddress litemallAddress = addressService.query(userId, address.getId());
            if (litemallAddress == null) {
                return RespUtil.fail();
            }

            if (address.getIsDefault()) {
                // 重置其他收货地址的默认选项
                addressService.resetDefault(userId);
            }

            address.setUserId(userId);
            addressService.update(address);
        }
        Map<String,Object> data = new HashMap<>();
        data.put("id", address.getId());
        return RespUtil.success(data);
    }

    /**
     * @api {get} /address/update 修改收货地址
     * @apiParam {number} id  地址id
     * @apiParam {String} province  省
     * @apiParam {String} city  市
     * @apiParam {String} village  区/县
     * @apiParam {String} userName 收货人姓名
     * @apiParam {number} gender 收货人性别
     * @apiParam {String} phone 收货人手机号
     * @apiParam {number} isDefault 是否默认地址
     * @apiParam {String} address 收货地址
     * @apiParam {String} detail 详细地址门牌号
     * @apiParam {number} lng 经度
     * @apiParam {number} lat 纬度
     * @apiGroup 用户地址
     * @apiVersion 0.1.0
     * @apiDescription 用户修改收货地址
     * @apiSuccess {int} code 请求状态码，0表示成功,其它参考状态码文档
     * @apiSuccess {String} message 结果消息说明
     * @apiSuccess {boolean} success 请求是否成功
     * @apiSuccess {Object} data 请求响应的数据
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code": "请求状态码，0表示成功，其它参考状态码文档",
     *     "success": "请求是否成功",
     *     "timestamp": "服务器当前时间戳10位精确到秒",
     *     "message": "请求成功/失败说明",
     *     "data": "请求响应数据，对象或数组"
     * }
     */
    @RequestMapping("/update")
    public BaseResult updateAddress(@LoginUser Integer userId, EjiaUserAddressInfo addressInfo) {
        return addAddress(userId, addressInfo);
    }

    /**
     * @api {post} /address/delete 删除收货地址
     * @apiParam {number} id 要删除的收货地址id，删除多个则id用英文逗号分隔，例如：1,3,4
     * @apiGroup 用户地址
     * @apiVersion 0.1.0
     * @apiDescription 用户删除收货地址
     * @apiSuccess {Object} Object 删除结果
     * @apiSuccess {int} code 请求状态码，0表示成功,其它参考状态码文档
     * @apiSuccess {String} message 结果消息说明
     * @apiSuccess {boolean} success 请求是否成功
     * @apiSuccess {Object} data 请求响应的数据
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code": "请求状态码，0表示成功，其它参考状态码文档",
     *     "success": "请求是否成功",
     *     "timestamp": "服务器当前时间戳10位精确到秒",
     *     "message": "请求成功/失败说明",
     *     "data": "请求响应数据，对象或数组"
     * }
     */
    @PostMapping("delete")
    public BaseResult delete(@LoginUser Integer userId, LitemallAddress address) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        Integer id = address.getId();
        if (id == null) {
            return RespUtil.fail();
        }
        LitemallAddress litemallAddress = addressService.query(userId, id);
        if (litemallAddress == null) {
            return RespUtil.success("已删除");
        }

        addressService.delete(id);
        return RespUtil.success();
    }


    /**
     * @api {get} /address/defaultAddr 获取默认收货地址
     * @apiGroup 用户地址
     * @apiVersion 0.1.0
     * @apiDescription 用户的默认收货地址详情信息
     * @apiSuccess {int} code 请求状态码，0表示成功,其它参考状态码文档
     * @apiSuccess {String} message 结果消息说明
     * @apiSuccess {boolean} success 请求是否成功
     * @apiSuccess {Object} data 请求响应的数据
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code": "请求状态码，0表示成功，其它参考状态码文档",
     *     "success": "请求是否成功",
     *     "timestamp": "服务器当前时间戳10位精确到秒",
     *     "message": "请求成功/失败说明",
     *     "data": {
     *         "address": {
     *             "id": "收货地址ID",
     *             "userId": "用户ID",
     *             "province": "省",
     *             "city": "市",
     *             "village": "区/县",
     *             "userName": "收货人姓名",
     *             "gender": "收货人性别",
     *             "phone": "收货人手机号",
     *             "isDefault": "是否是默认地址",
     *             "address": "收货地址",
     *             "detail": "详细地址门牌号",
     *             "lng": "经度",
     *             "lat": "纬度"
     *         }
     *     }
     * }
     */
    @RequestMapping("/defaultAddr")
    public BaseResult getUserDefaultAddress(@LoginUser Integer userId) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        LitemallAddress address = addressService.findDefault(userId);
        Map<String,Object> data = new HashMap<>();
        data.put("address", EjiaUserAddressInfo.getInstance(address));
        return RespUtil.success(data);
    }

}

